package com.yimils.core.sys.dto;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import com.yimils.core.sys.entity.RoleResourceEntity;
import com.yimils.core.sys.service.RoleResourceService;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class RoleResourceDto {

    @Resource(name = "roleResourceService")
    private RoleResourceService roleResourceService;

    //实体转数组
    public List<Long> entitiesToArray(List<RoleResourceEntity> roleRes) {
        List<Long> array = new ArrayList<>();
        for (RoleResourceEntity roleRe : roleRes) {
            if (roleRe.getActive().equals(1)) {
                array.add(roleRe.getResourceId());
            }
        }
        return array;
    }

    //数组转实体
    public List<RoleResourceEntity> arrayToEntities(ReqResource reqParams) {
        QueryWrapper<RoleResourceEntity> qw = new QueryWrapper<>();
        qw.eq("roleId", reqParams.getRoleId());
        List<RoleResourceEntity> list = roleResourceService.list(qw);
        List<Long> roleResIds = list.stream().map(RoleResourceEntity::getResourceId).collect(Collectors.toList());
        List<Long> newResIds = new ArrayList<>(reqParams.getRoleRes());

        List<RoleResourceEntity> newList = new ArrayList<>();

        newResIds.removeAll(roleResIds);

        for (Long newResId : newResIds) {
            RoleResourceEntity entity = new RoleResourceEntity();
            entity.setRoleId(reqParams.getRoleId());
            entity.setActive(1);
            entity.setResourceId(newResId);
            roleResourceService.saveOrUpdate(entity);
        }

        list = roleResourceService.list(qw);
        Iterator<RoleResourceEntity> iterator = list.iterator();
        while (iterator.hasNext()) {
            RoleResourceEntity roleResourceEntity = iterator.next();
            for (Long id : reqParams.getRoleRes()) {
                if (roleResourceEntity.getResourceId().equals(id)) {
                    roleResourceEntity.setActive(1);
                    newList.add(roleResourceEntity);
                }
            }
        }

        return newList;
    }

}
